<?
    require_once("config.php");
    require_once("objects/form_elements.php");
    require_once("objects/option_panel.php");
    
    if (!AuthManager::CheckPermissions(AuthConstants::ADMINISTRATORS)) {
        ErrorMessage::Show("Permissions Error","You don't have permission to access this resource.<br /><a href='javascript:history.back(-1)'>&laquo; Back</a>");
        die();
    }
    
    
    if ($_POST) {
        $settings = DBM::FetchAllRows("SELECT setting_name FROM settings ORDER BY setting_name ASC;");
        $tsettings = array();

        foreach ($settings as $setting) {
            $tsettings[$setting['setting_name']] = 1;
        }
        
        foreach ($_POST as $var => $value) {
            if ($tsettings[$var]) {
                $query = "UPDATE settings SET setting_value = '$value' WHERE setting_name LIKE '$var';";
                DBM::Execute($query);
                unset ($tsettings[$var]); 
            }
            else {
                $query = "INSERT INTO settings (setting_name, setting_value) VALUES ('$var','$value');";
                DBM::Execute($query);
            }
        }
        foreach ($tsettings as $var => $value) {
            if (strpos($var,"enabled") !== false) {
                $query = "UPDATE settings SET setting_value = '' WHERE setting_name = '$var';";
                DBM::Execute($query);
            }
        }
        
        header("Location: admin_settings.php");
    }
    else {
        Functions::PrintHeader("Edit Sitewide Settings");
        
        if (SettingManager::GetSetting("debug_superadmin") && SettingManager::GetSetting("debug_superadmin") != AuthManager::GetUsername()) {
            ErrorMessage::Show("Settings Restricted","Sorry, the administrator has disabled the ability to edit settings.");
            Functions::PrintFooter();
            die();
        }
        
        $message = "DynaText is a system used for dynamically changing the value of a string.  It can be used to bind variables from a database, from server variables, or from other settings.  Below is information about how to use DynaText in the fields below.<br><br><dl>
        <dt>(%)Server Vars</dt>
        <dd>To bind to any server variables (what you would see in the \$_SERVER array), enclose the variable name with a %.  For example, to bind to the SERVER_NAME variable, then type: %SERVER_NAME%</dd>
        
        <dt>(#) Database Vars</dt>
        <dd>Binding to database variables is specific based on the setting.  Since the data is actually set at runtime, you can specify only a column, then the application will pass the valid values.  Settings below will indicate which database variables can be bound too for that specific setting.  To bind to a database variable, enclose it with #.  For example, to bind to a database column 'email', you would type #email#</dd>
        
        <dt>(@)Setting Vars</dt>
        <dd>To bind to another setting (which is preferable for the maps section), enclose the setting name in a @.  To bind to the application title, type @application_title@</dd>
        
        <dt>(!)Resolving Links</dt>
        <dd>DynaText can also be used to resolve links for inserting them into E-Mails.  To do this, enclose the page in !.  For Example, to link to the login page (login.php), you would type !login!</dd><br><br>To hide this message, disable 'Show DynaText Help' in Basic Settings below.";
        
        if (SettingManager::GetSetting("show_dynatext_help") == "Yes")
            InfoMessage::Show("Information about DynaText",$message);
            
            
        ?>
        <form method="POST" action="admin_settings.php">
            <?
                $basicsettings = new OptionPanel("Basic Settings");
                $basicsettings->AddOption("Application Title",new TextField("application_title"));
                $basicsettings->AddOption("Administrator E-Mail",new TextField("admin_email"));
                $basicsettings->AddOption("Default State",new TextField("default_state"));
                $themes = new DropdownMenu("active_theme");
                foreach (ThemeManager::GetAvailableThemes() as $theme) {
                    $themes->AddOption($theme);
                }
                $basicsettings->AddOption("Active Theme",$themes);
                $showdynatext = new DropdownMenu("show_dynatext_help");
                $showdynatext->AddOption("Yes");
                $showdynatext->AddOption("No");
                $basicsettings->AddOption("Show DynaText Help",$showdynatext);
                $showvarnames = new DropdownMenu("show_varnames");
                $showvarnames->AddOption("Yes");
                $showvarnames->AddOption("No");
                $basicsettings->AddOption("Show Variable Names",$showvarnames);
                $basicsettings->AddOption("Max Listing Idle Time (days)",new TextField("max_listing_idle_time"));
                echo $basicsettings;
                
                $listingimagesettings = new OptionPanel("Listing Images",true);
                $listingimagesettings->AddComment("These settings allow you to customize how images are stored.  In most cases the defaults will suffice, however if you have space or bandwidth constraints then you may want to change these settings.");
                $listingimagesettings->AddOption("Maximum # Images per Listing<br>(0 for infinite)",new TextField("listing_images_quota"));
                $listingimagesettings->AddOption("Images Per Row on Listing Page",new TextField("listing_images_per_row"));
				$yesno = new DropdownMenu("listing_images_allowcopy");
                $yesno->AddOption(0,"No");
                $yesno->AddOption(1,"Yes");
                $listingimagesettings->AddOption("Copy Images when Copying Listings?",$yesno);
                $imagetypes = new DropdownMenu("listing_images_format");
                $imagetypes->AddOption('png','PNG (better quality, slightly larger file size)');
                $imagetypes->AddOption('jpg-50','Low Quality JPEG');
                $imagetypes->AddOption('jpg-75','Medium Quality JPEG');
                $imagetypes->AddOption("jpg-100","High Quality JPEG");
                $listingimagesettings->AddOption("Image Format",$imagetypes);
                $listingimagesettings->AddOption("Image Width",new TextField("listing_images_width"));
                $listingimagesettings->AddOption("Image Height",new TextField("listing_images_height"));
                $listingimagesettings->AddOption("Thumbnail Width",new TextField("listing_images_thumbnail_width"));
                $listingimagesettings->AddOption("Thumbnail Height",new TextField("listing_images_thumbnail_height"));
                echo $listingimagesettings;
                
                $debugsettings = new OptionPanel("Debug",true);
                $debugsettings->AddComment("These settings are for DEVELOPMENT PURPOSES ONLY.  Do NOT enable debugging in a production environment.");
                $debugsettings->AddComment("The Superadmin, if specified, is the only person who can modify the system settings (ie: this page).");
                $yesno = new DropdownMenu("debug_resize_window");
                $yesno->AddOption(0,"No");
                $yesno->AddOption(1,"Yes");
                $debugsettings->AddOption("Auto-Reisze Window On Load",$yesno);
                $debugsettings->AddOption("Window Width",new TextField("debug_window_width"));
                $debugsettings->AddOption("Window Height",new TextField("debug_window_height"));
                $debugsettings->AddOption("Superadmin",new TextField("debug_superadmin"));
                echo $debugsettings;
              
                $guestsettings = new OptionPanel("Guest Accounts",true);
                $guestsettings->AddComment("<b>Note:</b> Disabling guest accounts only disables the ability to request a guest account when you aren't logged in.  Guest accounts are necessary for landlords to have access.  Unless you plan on manually creating an account for every landlord, leave guest accounts enabled.");
                $guestsettings->AddComment("<hr />If you would rather not receive E-Mails when a guest account is requested, then change 'E-Mail Notifications to Admin' to NO.  Note, however, that this will require an administrator to log in to the system in order to check for new guest account requests.");
                $guestsettings->AddOption("Days Valid",new TextField("guest_accounts_valid_for"));
                $yesno = new DropdownMenu("guest_accounts_email_admin");
                $yesno->AddOption(0,"Off");
                $yesno->AddOption(1,"On");
                $guestsettings->AddOption("E-Mail Notifications to Admins",$yesno);
                $guestsettings->AddOption("Request E-Mail",new Textarea("guest_accounts_request_email"));
                $guestsettings->AddOption("Confirmation E-Mail",new Textarea("guest_accounts_confirmation_email"));
                $guestsettings->AddOption("Password Reset Request",new Textarea("guest_accounts_password_reset"));
                $guestsettings->AddOption("Password Reset Request Complete",new Textarea("guest_accounts_password_hasbeen_reset"));
                echo $guestsettings;
                
                $mailsettings = new OptionPanel("Outgoing Mail",true);
                $mailsettings->AddComment("All outgoing mail will be sent with the name matching the application title (Currently " . SettingManager::GetSetting('application_title') . ") and with an E-Mail address specified below as 'Send Mail from E-Mail' (Currently: ". SettingManager::GetSetting('outgoing_mail_from_address'));
                $mailsettings->AddComment("<hr />Common ports are<br><b>25</b>: No Encryption<br><b>465</b>: SSL<br><b>587</b>: TLS");
                $mailsettings->AddOption("SMTP Server",new TextField("outgoing_mail_server"));
                $mailsettings->AddOption("Server Port",new TextField("outgoing_mail_port"));
                $encryptions = new DropdownMenu("outgoing_mail_encryption");
                $encryptions->AddOption("none","None");
                $encryptions->AddOption("ssl","SSL");
                $encryptions->AddOption("tls","TLS");
                $mailsettings->AddOption("Encryption Type",$encryptions);
                $mailsettings->AddOption("Send Mail From E-Mail",new TextField("outgoing_mail_from_address"));
                $mailsettings->AddOption("SMTP Username",new TextField("outgoing_mail_username"));
                $mailsettings->AddOption("SMTP Password",new PasswordField("outgoing_mail_password"));
                echo $mailsettings;

                $googlemapspanel = new OptionPanel("Google Maps",true);
                $keyfield = new TextField("google_maps_api_key");
                $keyfield->SetAttribute("class","wide");
                $srcfield = new TextField("google_maps_api_src");
                $srcfield->SetAttribute("class","wide");
                $googlemapspanel->AddOption("API Source",$srcfield);
                $googlemapspanel->AddOption("API Key",$keyfield);
                $googlemapspanel->AddOption("School Address",new TextField("google_maps_school_address"));
                $zoomselection = new DropdownMenu("google_maps_default_zoom");
                for ($x = 15; $x > 0; $x--) $zoomselection->AddOption($x,($x == 15 ? "$x (All the way in)" : ($x == 1 ? "$x (All the way out)" : null)));
                $googlemapspanel->AddOption("Default Zoom Level",$zoomselection);
                echo $googlemapspanel;
            
                $concertopanel = new OptionPanel("Concerto Options",true);
                $serverfield = new Textfield("concerto_server");
                $serverfield->attributes->size = 35;
                $concertopanel->AddOption("Concerto Server",$serverfield);
                $feedid = new Textfield("concerto_feed_id");
                $feedid->attributes->size = 10;
                $concertopanel->AddOption("Feed ID",$feedid);
                //echo $concertopanel;
                
                $settings = array($basicsettings,$listingimagesettings,$debugsettings,$guestsettings,$mailsettings,$googlemapspanel);
                
                foreach (SettingManager::GetCustomPanels() as $panel) {
                    echo $panel;
                    $settings[] = $panel;
                }
            ?>
            <hr class='wide' />
            <input type='reset' value='Revert' /><input type='submit' value='Save Changes' />
            <br>
        </form>
        <script type='text/javascript'>
            var sections = {
                <?
                    foreach ($settings as $settingpanel) {
                        echo $settingpanel->attributes->name . " : new Array('" . implode("','",$settingpanel->ChildOptions()) . "'),\n";
                    }
                ?>
            };
            function toggleEnabled(section) {
                var elements = sections[section];
                if (elements && elements.length > 0) {
                    if ($(section).getAttribute('disabled')) $(section).removeAttribute('disabled');
                    else $(section).setAttribute('disabled','disabled');
                    
                    for (var x = 0; x < elements.length; x++) {
                        // convert into an actal DOM element
                        if (elements[x].length == 0) continue;
                        
                        element = $(elements[x]);
                        if (element && element.getAttribute) {
                            if (element.getAttribute('disabled'))
                                element.removeAttribute('disabled'); // enable
                            else
                                element.setAttribute('disabled','disabled');   // disable
                        }
                    }
                }
            }
        </script>
        <?
        Functions::PrintFooter();
    }
?>
